package com.mycase.im.boot.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mycase.im.boot.entity.database.ImCircle;
import com.mycase.im.boot.entity.database.ImMessage;
import com.mycase.im.boot.entity.database.ImUser;
import com.mycase.im.boot.entity.database.ImUserFriend;
import com.mycase.im.boot.service.CircleService;
import com.mycase.im.boot.service.MessageService;
import com.mycase.im.boot.service.UserFriendService;
import com.mycase.im.boot.service.UserService;
import com.mycase.im.boot.entity.communication.ResponseMessage;
import com.mycase.im.boot.utils.FileLoadUtil;
import com.mycase.im.boot.utils.UUIDUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;

import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.List;

import static com.mycase.im.boot.entity.communication.ResponseMessage.error;
import static com.mycase.im.boot.entity.communication.ResponseMessage.success;

/**
 * @Author ZhuHJay
 * @Date 2021/8/2 17:13
 */
@RestController
@Validated
@RequestMapping("/api/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private UserFriendService userFriendService;
    @Autowired
    private MessageService messageService;
    @Autowired
    private CircleService circleService;
    @Autowired
    private FileLoadUtil fileLoadUtil;

    @GetMapping("/list")
    public ResponseMessage getUserList(
            @NotBlank(message = "请求失败, 请重试") String id){

        List<ImUser> userList = userService.getUserList(id);

        return success().appendData("userList", userList);
    }

    @GetMapping("/friendList")
    public ResponseMessage getFriendList(
            @NotBlank(message = "请求失败, 请重试") String id){

        // 获取该用户的好友列表
        List<ImUserFriend> friendList = userFriendService.getFriendList(id);

        // 获取需要的信息
        friendList.forEach(friendInfo -> {
            // 获取好友信息
            ImUser imUser = userService.getUserInfoById(friendInfo.getFriendId());
            friendInfo.setImUser(imUser);
            // 获取与该好友的聊天记录
            List<ImMessage> messageRecord = messageService.getMessageRecord(id, friendInfo.getFriendId());
            // 放心存放, 没查到也会返回空集合
            friendInfo.setChatRecord(messageRecord);
            // 获取本人未读取的消息条数(未读就是好友发信息给我, 我没有读取)
            Integer unReadCount = messageService.getMessageUnReadCount(friendInfo.getFriendId(), id);
            // 防止空指针异常, 使用三元运算
            friendInfo.setUnReadCount(unReadCount == null ? 0 : unReadCount);
            // 动态信息的获取
            List<ImCircle> dynamics = circleService.findDynamicListByUserId(imUser);
            friendInfo.setDynamics(dynamics);
        });

        return success().appendData("friendList", friendList);
    }

    @GetMapping("/getSearchInfo")
    public ResponseMessage getSearchInfo(
            @NotBlank(message = "请求失败, 请重试") String account){

        QueryWrapper<ImUser> imUserQueryWrapper = new QueryWrapper<>();
        imUserQueryWrapper
                .eq("account", account)
                // 只获取 头像、昵称、id信息
                .select("id", "avatar", "nike_name");

        // 按照条件查询用户信息
        ImUser imUser = userService.getOne(imUserQueryWrapper);

        // 判断数据是否为空
        if( imUser == null ){
            return error();
        }

        return success().appendData("searchUserInfo", imUser);
    }

    @PostMapping("/update/mine")
    public ResponseMessage updateInformation(
            @NotBlank(message = "请求失败, 请重试") String id,
            @RequestParam(value = "nikeName", required = false)String nikeName,
            @RequestParam(value = "sign", required = false)String sign,
            @RequestPart(value = "file", required = false)MultipartFile file) throws Exception {

        final int nikeNameLength = 8;
        final int signLength = 16;
        final String imgPath = ResourceUtils.getURL("classpath:").getPath() + "static/img";

        String fileName = "";

        // 进行数据的空判断, 以及数据的校验
        if( StringUtils.hasLength(nikeName) && nikeName.trim().length() <= nikeNameLength ){
            ResponseMessage.error("昵称的长度不能超过" + nikeNameLength + "位");
        }
        if( StringUtils.hasLength(sign) && sign.trim().length() <= signLength ){
            ResponseMessage.error("签名的长度不能超过" + signLength + "位");
        }
        if( !file.isEmpty() ){
            fileName = fileLoadUtil.fileUpload(file, imgPath, new String[]{"jpg", "png", "ico"});
        }
        ImUser user = new ImUser();
        user.setId(id);
        user.setNikeName( StringUtils.hasLength(nikeName) ? nikeName.trim() : null );
        user.setSign( StringUtils.hasLength(sign) ? sign.trim() : null );
        user.setAvatar( StringUtils.hasLength(fileName) ? "/static/img/" + fileName : null );

        // 只要有一个不为空值, 那么才进行修改
        if( StringUtils.hasLength(user.getNikeName()) ||
                StringUtils.hasLength(user.getSign()) ||
                StringUtils.hasLength(user.getAvatar()) ) {
            userService.updateById(user);
        }
        return ResponseMessage.success();
    }


    @PostMapping("/update/friend/remark")
    public ResponseMessage updateFriendRemark(
            @NotBlank(message = "请求失败, 请重试") String id,
            @NotBlank(message = "请求失败, 请重试") String friendId,
            @Size(min = 1, max = 8, message = "备注不能为空并且最大长度为8") String remark){

        // 验证好友是否存在
        if( !userFriendService.isFriendRelation(id, friendId) ){
            return ResponseMessage.error("不存在该好友, 请重试");
        }
        userFriendService.setFriendRemark(id, friendId, remark);
        return ResponseMessage.success();
    }

    @PostMapping("/delete/friend/{friendId}")
    public ResponseMessage deleteFriend(
            @NotBlank(message = "请求失败, 请重试") String id,
            @PathVariable("friendId")String friendId){

        // 验证好友是否存在
        if( !userFriendService.isFriendRelation(id, friendId) ){
            return ResponseMessage.error("不存在该好友, 请重试");
        }
        // 进行好友关系的解绑
        userFriendService.cutFriendRelation(id, friendId);
        return ResponseMessage.success("好友已关系解除");
    }

}
